import {getUserTempId} from "@/utils/userabout";
import {reqCode, reqUserInfo, reqUserLogin, reqUserLogout, reqUserRegister} from "@/api";
const state = {
    userTempId:getUserTempId(),
    code:'',
    token:localStorage.getItem('token_key'),
    userInfo:{}


}
const mutations = {
    SET_CODE(state,code){
        state.code =code
    },
    SET_TOKEN(state,token){
        state.token = token
    },
    SET_USERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    REMOVE_TOKEN_USERINFO(state){
        state.token=''
        state.userInfo={}
    }
}
const actions = {
    //获取验证码
    async getCode({commit},phone){
        const result=await reqCode(phone)
        if(result.code === 200){
            commit('SET_CODE',result.data)
            return result.data
        }else{
            return Promise.reject(new Error('failed'))
        }

    },
    //用户注册
    // eslint-disable-next-line no-unused-vars
    async getUserRegister({commit},userInfo){
        const result= await reqUserRegister(userInfo)
        if(result.code === 200){
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //用户登陆获取到token
    async getUserLogin({commit},userInfo){
        const result=await reqUserLogin(userInfo)
        if(result.code === 200){
            commit('SET_TOKEN',result.data.token)//这是为了第一次登陆显示做准备
            localStorage.setItem('token_key',result.data.token)//这是为了之后刷新页面不会丢失token信息，
            return 'ok'

        }else {
            return Promise.reject(new Error('failed'))
        }



    },
    //有token的情况下，获取用户信息
    async getUserInfo({commit}){
        const result = await reqUserInfo()
        if (result.code === 200) {
            commit('SET_USERINFO',result.data)
            return 'ok'
        }else {
            return Promise.reject(new Error('failed'))
        }
    },
    //清除token和userInfo
    getRemoveTokenAndUserInfo({commit}){
        localStorage.removeItem('token_key')
        commit('REMOVE_TOKEN_USERINFO')
    },
    //退出登陆
    // eslint-disable-next-line no-unused-vars
    async getUserLogout({commit,dispatch}){
        const result = await reqUserLogout()
        if (result.code === 200){
            //退出登陆成功，清除token信息userInfo信息
            dispatch('getRemoveTokenAndUserInfo')
            return 'ok'

        }else {
            return Promise.reject(new Error('failed'))
        }
    },
}
const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters
}
